#pragma once

#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <unistd.h>
#include <strings.h>
#include "nocopy.hpp"

static const uint16_t default_port = 8888;
static int default_fd = -1;

class UdpServer : public nocopy
{
public:
    UdpServer(const std::string& ip, uint16_t port = default_port)
    :_ip(ip), _port(port), _sockfd(default_fd)
    {}

    void Init()
    {
        //1. 创建套接字socket，创建了文件细节
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "socket err," << errno << "," << strerror(errno) << std::endl;
            exit(2);
        }
        std::cout << "socket success, sockfd:" << _sockfd << std::endl;

        //2. 绑定。别人如何找到你呢？ 指定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));//指定内存全部清零
        local.sin_family = AF_INET;//创建的网络使用的协议家族是AF_INET
        local.sin_port = _port;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());//到这里把结构体填完了
        //但是这个结构体没有设置到内核中，这里这个local只是栈中的一个变量


        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n != 0)
        {
            std::cout << "bind err," << errno << "," << strerror(errno) << std::endl;
            exit(3);
        }
    }
    void Start()
    {
        //服务器永远不退出
        char buffer[1024];
        for(;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;
                sendto(_sockfd, &buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
            }
        }
    }
    ~UdpServer(){}
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};